<template>
  <div>
    <el-button type="primary" @click="showUploadDialog">上传文件</el-button>
    <el-dialog v-model="uploadDialogVisible" title="上传文件">
      <form class="upload-container" enctype="multipart/form-data" method="POST">
        <input type="file" name="file" @change="handleFileUpload">
        <el-button type="primary" @click="uploadFile" :disabled="!selectedFile">上传文件</el-button>
      </form>
    </el-dialog>

    <el-table :data="fileList" :border="true">
      <el-table-column label="名称" prop="name"></el-table-column>
      <el-table-column label="大小" prop="size"></el-table-column>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button @click="openfile(row)" size="mini">查看</el-button>
          <el-button @click="handleDelete(row)" type="danger" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @current-change="handleCurrentChange"
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from '../axios';
import { ElMessage } from 'element-plus';

export default {
  setup() {
    const fileList = ref([]);
    const currentPage = ref(1);
    let pageSize = 10;
    const total = ref(0);
    const uploadDialogVisible = ref(false);
    const token = localStorage.getItem('token');
    const selectedFile = ref(null);

    const showUploadDialog = () => {
      uploadDialogVisible.value = true;
    };

    const handleFileUpload = (event) => {
      if (event.target.files.length > 0) {
        selectedFile.value = event.target.files[0];
      } else {
        console.error('未选择文件');
      }
    };

    const uploadFile = async () => {
      const formData = new FormData();
      formData.append('file', selectedFile.value);

      try {
        const response = await axios.post('./upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            // 'Authorization': `Bearer ${token}`
          }
        });
        if (response.data.success) {
          ElMessage.success(response.data.message);
          uploadDialogVisible.value = false;
          window.location.reload();
        } else {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        console.error(error);
        ElMessage.error(error);
      }
    };

    const handleDelete = async (row) => {
      try {
        const response = await axios.delete('./deletePDF', {
          headers: {
            'Authorization': `Bearer ${token}`,
          },
          params: {
            name: row.name
          }
        });
        if (response.data.success) {
          ElMessage.success(response.data.message);
          getFileList();
        } else {
          ElMessage.error(response.data.message);
          window.location.reload();
        }
      } catch (error) {
        console.error(error);
        ElMessage.error(error);
      }
    };


    const getFileList = async () => {
      try {
        const response = await axios.get('./getFileData', {
          headers: {
            // 'Authorization': `Bearer ${token}`,
            'Content-Type': 'multipart/form-data'
          }
        });
        fileList.value = response.data.files;
      } catch (error) {
        console.error(error);
        ElMessage.error('获取文件列表失败');
      }
    };

    const openfile = async(row) => {
      window.open(`http://localhost:3000/pdfs/${row.name}`, '_blank');
		};

    // const handleSizeChange = (val) => {
    //       const newPageCount = Math.ceil(total.value / val);
    //       if (currentPage.value > newPageCount) {
    //         currentPage.value = newPageCount;
    //       }
    //       pageSize = val 
    //       getFileList();
    // };

    const handleCurrentChange = (val) => {
          currentPage.value = val;
          getFileList();
    };

    onMounted(() => {
      getFileList();
    });
    

    return {
      fileList,
      currentPage,
      pageSize,
      total,
      uploadDialogVisible,
      selectedFile,
      showUploadDialog,
      handleFileUpload,
      uploadFile,
      handleDelete,
      openfile,
      handleCurrentChange,
      // handleSizeChange
    };
  }
};
</script>